package server;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Date;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;

import data.Data;

import net.bican.wordpress.Page;
import net.bican.wordpress.Wordpress;
import redstone.xmlrpc.XmlRpcFault;

public class PostWp {
	public static void postWp(String title,String description,ArrayList<String> tag,String domain) throws XmlRpcFault, IOException
	{
		DBCollection coll = Data.data("users");
		DBObject users = coll.findOne(new BasicDBObject("url",domain));
		if(users != null)
		{
			String username = users.get("username").toString();
		    String password = users.get("password").toString();
		    String xmlRpcUrl = domain+"/xmlrpc.php";
		    try {
		    	Wordpress wp = new Wordpress(username, password, xmlRpcUrl);
		    	Page recentPost = new Page();
			    recentPost.setDateCreated(new Date());
			    recentPost.setPost_status("publish");
			    recentPost.setWp_author("admin");
			    recentPost.setTitle(title);
			    
			    String keyword = "";
			    
			    if(tag.size() > 0)
			    {
			    	for (int i = 0; i < tag.size(); i++) {
			    		if(keyword.equals(""))
			    		{
			    			keyword = tag.get(i);
			    		} else {
			    			keyword += ","+tag.get(i);
			    		}
			    			
					}
			    }
			    if(!keyword.equals(""))
			    	recentPost.setMt_keywords(keyword);
	//		    XmlRpcArray keyword = new XmlRpcArray();
	//		    keyword.add("nosql");
	//		    recentPost.setCategories(keyword);
			    recentPost.setDescription(description);
			    
			    String result = wp.newPost(recentPost, false);
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
	}
}
